package com.feature50.clarity;

import com.feature50.clarity.misc.ClarityProgressMonitor;
import com.feature50.clarity.misc.SimpleClarityProgressMonitor;

import javax.swing.AbstractAction;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;

public abstract class FormAction extends AbstractAction {
    private Form form;
    private boolean disableUI;

    protected FormAction(String name, Form form) {
        this(name, form, false);
    }

    protected FormAction(String name, Form form, boolean disableUI) {
        super(name);
        this.form = form;
        this.disableUI = disableUI;
    }

    public final void actionPerformed(ActionEvent e) {
        boolean c = performAction(e);
        if (!c) return;

        setEnabled(false);

        final SimpleClarityProgressMonitor monitor = new SimpleClarityProgressMonitor();
        form.getFormContainer().disableUI(monitor);
        new Thread("FormAction background thread") {
            public void run() {
                final Map state = new HashMap();
                final boolean c = performActionInBackground(monitor, state);

                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        if (c) {
                            performActionFinished(state);
                        } else {
                            performActionBackgroundFailed(state);
                        }

                        setEnabled(true);
                        form.getFormContainer().enableUI();
                    }
                });
            }
        }.start();
    }

    public abstract boolean performAction(ActionEvent e);

    public boolean performActionInBackground(ClarityProgressMonitor monitor, Map state) { return true; };

    public void performActionFinished(Map state) {};

    public void performActionBackgroundFailed(Map state) {};
}
